package com.yunchi.utils;

import cn.hutool.core.util.NumberUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.file.FileStore;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * @Author: Crazer
 * @Date: 2023/7/6 13:55
 * @version: 1.0.0
 * @Description:
 */
public class SystemUtils {
    private static final Logger logger = LoggerFactory.getLogger(SystemUtils.class);

    public static void monitorCDisk(String requestUrl, String phone) {
        // 获取C盘的FileStore对象
        FileStore cDriveStore;
        try {
            Path cDrivePath = FileSystems.getDefault().getPath("C:");
            cDriveStore = Files.getFileStore(cDrivePath);

            // 获取C盘的总空间大小和已使用空间大小（以字节为单位）
            long totalSpace = cDriveStore.getTotalSpace();
            long unUsedSpace = cDriveStore.getUnallocatedSpace();
            long usedSpace = totalSpace - cDriveStore.getUnallocatedSpace();

            // 转换总空间大小和已使用空间大小为可读格式
            String formattedTotalSpace = formatSize(totalSpace);
            String formattedUnUsedSpace = formatSize(unUsedSpace);
            String formattedUsedSpace = formatSize(usedSpace);

            // 打印总空间大小和已使用空间大小
            // logger.info("C盘总空间大小: {}", formattedTotalSpace);
            // logger.info("C盘剩余空间大小: {}", formattedUnUsedSpace);
            // logger.info("C盘已使用空间大小: {}", formattedUsedSpace);

            int occupancyRatio = (int) (NumberUtil.div(unUsedSpace, totalSpace) * 100);
            String formattedContent = "";
            if (occupancyRatio < 20) {
                formattedContent = String.format("C盘可用率：【%d%% < 20%%】，C盘总空间大小：%s，C盘剩余空间大小：%s，C盘已使用空间大小：%s",
                        occupancyRatio, formattedTotalSpace, formattedUnUsedSpace, formattedUsedSpace);
                logger.error(formattedContent);
                SMSUtils.sendSMS(requestUrl, phone, formattedContent);
            } else {
                formattedContent = String.format("C盘可用率：【%d%% >= 20%%】，C盘总空间大小：%s，C盘剩余空间大小：%s，C盘已使用空间大小：%s",
                        occupancyRatio, formattedTotalSpace, formattedUnUsedSpace, formattedUsedSpace);
                logger.info(formattedContent);
            }
        } catch (Exception e) {
            logger.error("监控C盘空间出现异常：\n", e);
        }

    }

    // 格式化文件大小
    private static String formatSize(long size) {
        long kilo = 1024;
        long mega = kilo * 1024;
        long giga = mega * 1024;

        if (size < kilo) {
            return size + " B";
        } else if (size < mega) {
            return String.format("%.2f KB", (double) size / kilo);
        } else if (size < giga) {
            return String.format("%.2f MB", (double) size / mega);
        } else {
            return String.format("%.2f GB", (double) size / giga);
        }
    }
}
